/* eslint-disable */
// Otherwise webpack can fail silently
// https://github.com/facebook/create-react-app/issues/8014

// Reference for service-worker.js: https://developers.google.com/web/tools/workbox/modules

import {serviceWorkerFetchListener} from 'sync-message';
import {clientsClaim, skipWaiting} from 'workbox-core';
import {ExpirationPlugin} from 'workbox-expiration';
import {precacheAndRoute} from 'workbox-precaching';
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';

// Intercepts sync-message requests to support things like input() and sleep()
// Not relating to caching etc.
addEventListener('fetch', serviceWorkerFetchListener());

clientsClaim();
skipWaiting();

if (process.env.REACT_APP_PRECACHE) {
  // precacheAndRoute: Precaches all of the assets generated by your build process.
  // Their URLs are injected into the manifest variable below.
  // This variable (self.__WB_MANIFEST) must be present somewhere in your service worker file,
  // even if you decide not to use precaching. See https://cra.link/PWA
  precacheAndRoute(self.__WB_MANIFEST);

  registerRoute(
    ({url}) => {
      const urlString = url.toString();
      return (
        urlString.startsWith('https://cdn.jsdelivr.net/') || // Pyodide
        urlString.startsWith('https://pyodide-cdn2.iodide.io') || // Only used when we are testing bleeding-edge pyodide
        urlString.startsWith('https://futurecoder-io--') || // Firebase preview deployments
        url.hostname.endsWith('futurecoder.io') ||
        url.hostname.includes('localhost') ||
        url.hostname.includes('127.0.0.1')
      );
    },
    new StaleWhileRevalidate({
      cacheName: 'everything',
      plugins: [
        new ExpirationPlugin({maxEntries: 30}),
        new CacheableResponsePlugin(
          {statuses: [0, 200]}
          // ^ Q: What's status 0 mean?
          // ^ A: It's an opaque response, and it relates to third-party resources (and CORS).
          // https://github.com/alexmojaki/futurecoder/pull/313/files/f5f0fded9f44fefd0bf44b99ee45f54a8badc272#r829408930
        ),
      ],
    }),
  );
}
